package com.koron.common.core.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author twcao
 * @description easyexcel工具类
 * @project gdheam
 * @classname EasyExcelUtils
 * @date 2020/7/24 16:35
 */
@Slf4j
public class EasyExcelUtils {

    /**
     * 导出多个sheet的excel
     *
     * @param resp      接口相应
     * @param sheetList sheet数据， key:value  ---> sheet名称: sheet数据列表
     * @param fileName  浏览器下载的文件名 需要文件后缀
     */
    public static void export(HttpServletResponse resp, Map<String, List<?>> sheetList, String fileName) {
        Assert.notEmpty(sheetList, "sheet data is empty");
        Assert.hasText(fileName, "file name is empty");
        ExcelWriter excelWriter = null;
        try (OutputStream outputStream = resp.getOutputStream()) {
            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            excelWriter = EasyExcelFactory.write(fileName).file(outputStream).build();
            int i = 1;
            for (Iterator<Map.Entry<String, List<?>>> iterator = sheetList.entrySet().iterator(); iterator.hasNext(); i++) {
                Map.Entry<String, List<?>> entry = iterator.next();
                List<?> list = entry.getValue();
                if (CollectionUtils.isEmpty(list)) {
                    continue;
                }
                WriteSheet writeSheet = EasyExcelFactory.writerSheet(i, entry.getKey())
                        .registerWriteHandler(new HorizontalCellStyleStrategy())
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .head(list.get(0).getClass()).build();
                excelWriter.write(list, writeSheet);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }

    }

    /**
     * 导出excel
     * @param sheetName 默认sheet名称
     * @param list 二维列表
     * @param fileName 浏览器下载的文件名 需要文件后缀
     */
    public static void export(HttpServletResponse resp, String sheetName, List<?> list, String fileName) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        try (OutputStream outputStream = resp.getOutputStream()) {
            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            EasyExcelFactory.write(outputStream)
                    .registerWriteHandler(new HorizontalCellStyleStrategy())
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet(sheetName)
                    .doWrite(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    public static String createTempFile(String ext) {
        return createTempFile(UUID.randomUUID().toString().replace("-", ""), ext);
    }

    public static String createTempFile(String fileName, String ext) {
        try {
            String templatePath = null;
            String userHome = System.getProperties().getProperty("user.dir");
            String workSpace = userHome + "/temp";
            File wsFile = new File(workSpace);
            if (!wsFile.exists()) {
                wsFile.mkdirs();
            }
            templatePath = wsFile + "/" + fileName + "." + ext;
            File template = new File(templatePath);
            if (!template.exists()) {
                Boolean result = template.createNewFile();
                Assert.isTrue(result,"创建文件失败！");
            }
            return templatePath;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static HorizontalCellStyleStrategy defaultStyles(){
        //表头样式策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //表头前景设置灰
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setBold(true);
        headWriteFont.setFontName("宋体");
        headWriteFont.setFontHeightInPoints((short) 12);
        headWriteCellStyle.setWriteFont(headWriteFont);

        //内容样式策略策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 设置背景颜色白色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        // 设置垂直居中为居中对齐
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置左右对齐为靠左对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置单元格上下左右边框为细边框
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        //创建字体对象
        WriteFont contentWriteFont = new WriteFont();
        //内容字体大小
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints((short) 13);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        // 初始化表格样式
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }
}
